package com.example.baijiebrower;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.webkit.WebSettingsCompat;
import androidx.webkit.WebViewFeature;

import com.example.baijiebrower.base.BaseActivity;
import com.example.baijiebrower.settings.Settings;
import com.example.baijiebrower.tools.FormData;
import com.example.baijiebrower.tools.Permissions;
import com.example.baijiebrower.update.CheckUpdateService;
import com.example.baijiebrower.update.UpdateDialog;

import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {
    @BindView(R.id.myweb)
    WebView myweb;
    private static final int REQUEST_CODE_INTERNET = 1;
    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 2;
    private static final String URL = "http://down.szbaijie.com:8880/project/dolibarr/htdocs/";
    private int backPressedCount = 1;
    /** 定义两次返回键的时间间隔，单位为毫秒s */
    private static final long TIME_INTERVAL = 2000;
    private static final int ANDROID_VERSION = 33;
    private long lastBackPressedTime;
//    private String username1 = null;
//    private String password1 = null;
    private String inputName = null;
    private String inputPassword = null;
    /** 是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值 */
    protected boolean useThemestatusBarColor = false;
    /** 是否使用状态栏文字和图标为暗色，如果状态栏采用了白色系，则需要使状态栏和图标为暗色，android6.0以上可以设置 */
    protected boolean useStatusBarColor = true;
    private UpdateDialog updateDialog;
    private FormData formData;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        File file = new File("/data/data/com.example.baijiebrower/data.json");
        initSharedPreferences();
        mContext = this;
        if (!isSetHttp(this) && formData.getHeader(mContext).isEmpty()){
            Intent intent = new Intent(this , Settings.class);
            startActivity(intent);
        }else {
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            Intent intent = new Intent(this, CheckUpdateService.class);
            startService(intent);
            IntentFilter filter = new IntentFilter("com.example.baijiebrower.ACTION_SHOW_UPDATE_DIALOG");
            LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
            CookieSyncManager.createInstance(this);
            loadUrl();
            setStatusBar();
            checkDarkMode(getApplicationContext());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (updateDialog != null && updateDialog.isShowing()){
            updateDialog.dismiss();
        }
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.example.baijiebrower.ACTION_SHOW_UPDATE_DIALOG")){
                String url = intent.getStringExtra("url");
                String versionName = intent.getStringExtra("versionName");
                String updateMessage = intent.getStringExtra("updateMessage");
                updateDialog = new UpdateDialog(MainActivity.this , url , versionName , updateMessage);
                updateDialog.setCanceledOnTouchOutside(false);
                updateDialog.show();
            }
        }
    };
    private void loadUrl() {
        // 获取Intent中的URL
        Intent intent = getIntent();
        String url = intent.getDataString();
        //String url = formData.getHeader(mContext);
        if (url == null) {
            if (formData.getHeader(mContext).isEmpty()) {
                formData.saveHeader(mContext, getResources().getStringArray(R.array.header)[0]);
                url = formData.getHttpValue(mContext, getResources().getStringArray(R.array.header)[0]);
            } else {
                url = formData.getHttpValue(mContext, formData.getHeader(mContext));
            }
        }

        // 加载URL

        myweb.getSettings().setJavaScriptEnabled(true);
        myweb.getSettings().setLoadWithOverviewMode(true);
        myweb.getSettings().setUseWideViewPort(true);
        myweb.getSettings().setDatabaseEnabled(true);
        myweb.getSettings().setDomStorageEnabled(true);
        myweb.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 启用缩放功能
        myweb.getSettings().setSupportZoom(true);
        myweb.getSettings().setBuiltInZoomControls(true);
        myweb.getSettings().setDisplayZoomControls(false);
        myweb.getSettings().setUseWideViewPort(true);
        myweb.getSettings().setLoadWithOverviewMode(true);
        myweb.loadUrl(url);
        myweb.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                if (!formData.getValue(mContext,formData.getHeader(mContext)).isEmpty() && !formData.getValueKey(mContext,formData.getHeader(mContext)).isEmpty()) {
                    String javascriptCode = "(function() {" +
                            "var usernameInput = document.getElementById('username');" +
                            "var passwordInput = document.getElementById('password');" +
                            "var loginButton = document.getElementsByClassName('button')[0];" +
                            "if (usernameInput && passwordInput) {" +
                            "    usernameInput.value = '" + formData.getValue(mContext,formData.getHeader(mContext)) + "';" +
                            "    passwordInput.value = '" + formData.getValueKey(mContext,formData.getHeader(mContext)) + "';" +
//                            "    loginButton.click();" +
                            "}" +
                            "}());";
                    myweb.evaluateJavascript(javascriptCode, null);
                }
                /*
                switch (url){
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/index.php":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/index.php?mainmenu=home&leftmenu=home":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/adherents/index.php?mainmenu=members&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/societe/index.php?mainmenu=companies&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/product/index.php?mainmenu=products&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/mrp/index.php?mainmenu=mrp&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/projet/index.php?mainmenu=project&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/comm/index.php?mainmenu=commercial&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/compta/index.php?mainmenu=billing&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/compta/bank/list.php?mainmenu=bank&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/accountancy/index.php?mainmenu=accountancy&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/hrm/index.php?mainmenu=hrm&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/ecm/index.php?idmenu=75&mainmenu=ecm&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/comm/action/index.php?idmenu=58&mainmenu=agenda&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/ticket/index.php?mainmenu=ticket&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/core/tools.php?mainmenu=tools&leftmenu=":
                    case "http://down.szbaijie.com:8088/project/dolibarr/htdocs/comm/index.php":
                        if (username1 != null && password1 != null) {
                            String javascriptCode = "(function() {" +
                                    "var usernameInput = document.getElementById('username');" +
                                    "var passwordInput = document.getElementById('password');" +
                                    "var loginButton = document.getElementsByClassName('button')[0];" +
                                    "if (usernameInput && passwordInput) {" +
                                    "    usernameInput.value = '" + username1 + "';" +
                                    "    passwordInput.value = '" + password1 + "';" +
//                            "    loginButton.click();" +
                                    "}" +
                                    "}());";
                            myweb.evaluateJavascript(javascriptCode, null);
                        }
                        break;
                    default:
                        break;
                } */
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (request.getMethod().equalsIgnoreCase("POST")) {
                    runOnUiThread(() -> saveFromdata());
                }
                return super.shouldInterceptRequest(view, request);

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                myweb.reload();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                long currentTime = System.currentTimeMillis();
                if (backPressedCount != 0 && currentTime - lastBackPressedTime <= TIME_INTERVAL) {
                    showExitDialog();
                } else {
                    // 如果 WebView 不能再返回，执行退出的操作
                    if (myweb.canGoBack()) {
                        myweb.goBack();
                    } else {
                        // 刷新页面
                        myweb.reload();
                    }
                }

                lastBackPressedTime = currentTime;
                backPressedCount++;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initSharedPreferences() {
        formData = new FormData();
        for (int i = 0; i <getResources().getStringArray(R.array.header).length; i++){
            formData.setHttpValue(this,getResources().getStringArray(R.array.header)[i], getResources().getStringArray(R.array.header_url)[i]);
        }
    }

    private void showExitDialog() {
        new AlertDialog.Builder(this)
                .setTitle("退出应用")
                .setMessage("确定退出？")
                .setPositiveButton("确定", (dialog, which) -> finish())
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .setNeutralButton("设置", (dialog, which) -> {
                    Intent intent = new Intent(MainActivity.this, Settings.class);
                    startActivity(intent);
                    finish();
                })
                .show();
    }

    private void saveFromdata() {
        String javascriptCode = "(function() {" +
                "var username = document.getElementById('username').value;" +
                "var password = document.getElementById('password').value;" +
                "var result = { username: username, password: password };" +
                "return result;" +
                "}())";

        myweb.evaluateJavascript(javascriptCode, value -> {
            // 在这里处理获取的表单数据
            try {
                JSONObject jsonArray = new JSONObject(value);
                inputName = jsonArray.getString("username"); // 获取第一个值
                inputPassword = jsonArray.getString("password"); // 获取第二个值
                if (!inputName.equals(formData.getValue(this,formData.getHeader(mContext))) || !inputName.equals(formData.getValueKey(this,formData.getHeader(mContext)))){
                    formData.saveFormData(this,formData.getHeader(mContext), inputName, inputPassword);
                }
//                if (!inputName.equals(username1) && !inputName.equals(password1)) {
//                    username1 = inputName;
//                    password1 = inputPassword;
//                    if (username1 != null && password1 != null && !username1.trim().isEmpty() && !password1.trim().isEmpty()) {
//                        Log.i("username", username1);
//                        Log.i("password", password1);
//                        // 保存 JSON 数据到文件
//                        String filePath = "/data/data/com.example.baijiebrower/data.json";
//                        File file = new File(filePath);
//                        FileWriter writer = new FileWriter(file);
//                        writer.write(value);
//                        writer.flush();
//                        writer.close();
//                        Log.i("Save JSON", "JSON data saved successfully to " + filePath);
//                        Toast.makeText(MainActivity.this, "账号密码已保存", Toast.LENGTH_SHORT).show();
//                    }
//                    else {
//                        Toast.makeText(MainActivity.this, "账号密码不能为空", Toast.LENGTH_SHORT).show();
//                    }
//                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }
    private boolean isSetHttp(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences("BAIJIESETHTTP", MODE_PRIVATE);
        return  sharedPreferences.getBoolean("setHttp", false);
    }

//    private void readDataFromFile() {
//        try {
//            File file = new File("/data/data/com.example.baijiebrower/data.json");
//            if (file.exists()) {
//                if (file.length() == 0) {
//                    // 文件存在且长度为0，表示文件为空
//                    Log.e("Json", "文件为空");
//                } else {
//                    // 文件存在但长度不为0，表示文件不为空
//                    FileInputStream fis = new FileInputStream(file);
//                    InputStreamReader isr = new InputStreamReader(fis);
//                    BufferedReader br = new BufferedReader(isr);
//
//                    StringBuilder jsonData = new StringBuilder();
//                    String line;
//                    while ((line = br.readLine()) != null) {
//                        jsonData.append(line);
//                    }
//
//                    br.close();
//
//                    // 解析 JSON 数据
//                    JSONObject jsonObject = new JSONObject(jsonData.toString());
//                    username1 = jsonObject.getString("username");
//                    password1 = jsonObject.getString("password");
//
//                    // 打印值
//                    Log.e("username", username1);
//                    Log.e("password", password1);
//                }
//            } else {
//                // 文件不存在
//                Log.e("Json", "文件不存在");
//            }
//        } catch (IOException | JSONException e) {
//            e.printStackTrace();
//        }
//    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予, 继续操作
                loadUrl();
            } else {
                // 如果权限被拒绝，执行退出的操作
                finish();
            }
        }
    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.touming));//设置状态栏背景色
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);//透明
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        } else {
            Toast.makeText(this, "低于4.4的android系统版本不存在沉浸式状态栏", Toast.LENGTH_SHORT).show();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && useStatusBarColor) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    private void checkDarkMode(Context context) {
        if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK) && Build.VERSION.SDK_INT >= ANDROID_VERSION) {
            WebSettingsCompat.setAlgorithmicDarkeningAllowed(myweb.getSettings(), true);
        }
    }
}